<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ganqqwerty
 * Date: 05.04.12
 * Time: 12:46
 * To change this template use File | Settings | File Templates.
 */
require_once("SemanticArticleFeedback.hooks.php");

global $wgHooks;
$wgHooks['smwStorePageData'][] = 'SAFHooks::smwStorePageData';
$wgHooks['ArticleFeedbackChangeRating'][] = 'SAFHooks::articleFeedbackChangeRating';

class SemanticArticleFeedback
{
    /**
     * @static
     * @param $id page_id for the page
     * @return float average vote
     */
    public static function calculateAvgVote($id)
    {
        $dbr = wfGetDB(DB_SLAVE);
        $table = 'article_feedback_pages';
        $vars = array('aap_total/aap_count AS aap_avg');
        $conds = array("aap_page_id" => $id);
        $options = array(
            'GROUP BY' => 'aap_page_id, aap_rating_id',
        );
        //$query = "SELECT  aap_count`  AS aap_avg FROM `article_feedback_pages` WHERE aap_page_id = 1 GROUP BY aap_page_id,  `aap_rating_id`";
        $res = $dbr->select($table, $vars, $conds, __METHOD__, $options);

        $sum = 0;
        if (!($res->valid()) || $res->numRows()<=0)
            return null;
        foreach ($res as $row)
        {
            $sum += $row->aap_avg;
        }
        $avgVote = $sum / 4;//FIXME 4 is wrong! sometimes the users do not vote for some criteria

        return $avgVote;
    }
}
